package com.shwread.android.qysw.activity.healthy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shwread.android.qysw.step.HealthyConfig;
import com.shwread.android.qysw.step.adapter.FriendPKAdapter;
import com.shwread.android.qysw.step.api.MyAsynctask;
import com.shwread.android.qysw.step.dto.HMMatch;
import com.shwread.android.qysw.step.dto.HMMatchsDto;
import com.shwread.android.qysw.step.model.UserHealthyModel;
import com.shwread.android.qysw.step.view.LoadMoreListView;
import com.shwread.android.qysw10000243.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import logic.constants.AppConfig;

/**
 * Created by Fantasy on 16/3/27.
 */
public class FriendPKActivity extends Activity {
    @InjectView(R.id.back_btn)
    ImageView backBtn;
    @InjectView(R.id.back_text)
    TextView backText;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.right_text)
    TextView rightText;
    @InjectView(R.id.right_img)
    ImageView rightImg;
    @InjectView(R.id.friend_pk_listview)
    LoadMoreListView friendPkListview;
    @InjectView(R.id.create_game_button)
    RelativeLayout createGameButton;

    public FriendPKAdapter friendPKAdapter;
    @InjectView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @InjectView(R.id.no_firend_game_layout)
    RelativeLayout noFirendGameLayout;
    private LinearLayoutManager linearLayoutManager;
    private boolean isHasMore = true;
    private int mPage = 1;
    private List<Object> mAllList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.healthy_friend_pk_activity);
        ButterKnife.inject(this);

        titleText.setText("友谊赛");
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        rightText.setVisibility(View.VISIBLE);
        rightText.setText("历史记录");
        rightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FriendPKActivity.this, FriendPKHistoryActivity.class);
                startActivity(intent);
            }
        });
        linearLayoutManager = new LinearLayoutManager(this);
        friendPkListview.setLayoutManager(linearLayoutManager);

        createGameButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FriendPKActivity.this, HealthyChooseFriendActivity.class);
                intent.putExtra("matchName", "J好友PK");
                intent.putExtra("matchException", "J好友PK");
                intent.putExtra("startTime", "");
                intent.putExtra("endTime", "");
                intent.putExtra("targetStep", "1000");
                intent.putExtra("gameType", "1");
                startActivity(intent);
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        mAllList = new ArrayList<>();
        friendPKAdapter = new FriendPKAdapter(FriendPKActivity.this, false);
        friendPKAdapter.init_data_list(mAllList);
        friendPkListview.setLoadMoreListViewAdapter(friendPKAdapter);

        friendPkListview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                int totalItemCount = linearLayoutManager.getItemCount();
                if (lastVisibleItem >= totalItemCount - 4 && dy >= 0 && isHasMore) {
                    refreshData(mPage);
                } else if (mAllList.size() < 4 && isHasMore) {
                    refreshData(mPage);
                }
            }
        });
        refreshData(1);

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mAllList.clear();
                refreshLayout.setRefreshing(false);
                refreshData(1);
                friendPKAdapter.notifyDataSetChanged();
            }
        });
    }

    public void refreshData(int page) {
        HashMap<String, String> params = new HashMap<>();
        params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
        params.put("enterpriseId", AppConfig.getEnterpriseId());
        params.put("page", page + "");
        params.put("pageSize", HealthyConfig.loadPageCount + "");
        params.put("isCreater", "2");
        params.put("type", "1");
        String unstartUrl = "/hzlqswserver/health/game/unStart";
        HashMap<String, String> hashMapUrl2 = new HashMap<>();
        hashMapUrl2.put("url", unstartUrl);
        MyAsynctask asynctask = new MyAsynctask(this, new MyAsynctask.RequestListener() {
            @Override
            public void requestSuccess(String result) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("returnObject");
                    Log.i("darren2", res);

                    if (TextUtils.isEmpty(res)) {
                        noFirendGameLayout.setVisibility(View.VISIBLE);
                    } else {
                        noFirendGameLayout.setVisibility(View.INVISIBLE);

                        HMMatchsDto hmMatchsDto = HMMatchsDto.parserJson(res);
                        List<HMMatch> hmMatches = hmMatchsDto.getHMMatchs();
                        if (hmMatches == null || hmMatches.size() == 0 && mPage == 1) {
                            noFirendGameLayout.setVisibility(View.VISIBLE);
                        }
                        mAllList.addAll(hmMatches);
                        friendPKAdapter.setTotal_data_list(mAllList);
                        friendPKAdapter.notifyDataSetChanged();
                        Log.i("darren", "size:----->" + hmMatchsDto.getHMMatchs().size());
                        if (hmMatchsDto.getHMMatchs().size() == HealthyConfig.loadPageCount) {
                            isHasMore = true;
                            mPage += 1;
                        } else {
                            isHasMore = false;
                        }
                        friendPKAdapter.setIsHasMore(isHasMore);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        asynctask.execute(hashMapUrl2, params);

    }
}
